package com.hsy.boot.service.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

/**
 * 数据源配置
 *
 * @author huoshengyu
 * @version 1.0
 * @date 2020/3/28 10:39
 */
@Slf4j
@Configuration
public class DataSourceConfig implements BeanFactoryPostProcessor, EnvironmentAware {
    private Environment env;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        String dbNameStr = env.getProperty("datasource.names");
        if (StringUtils.isEmpty(dbNameStr)) {
            throw new IllegalArgumentException("数据源必须配置");
        }
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;
        String[] dbNames = dbNameStr.split(",");
        for (String dbName : dbNames) {
            HikariConfig hikariConfig = new HikariConfig();
            hikariConfig.setDriverClassName(env.getProperty("datasource." + dbName + ".driver-class-name"));
            hikariConfig.setJdbcUrl(env.getProperty("datasource." + dbName + ".jdbc-url"));
            hikariConfig.setUsername(env.getProperty("datasource." + dbName + ".username"));
            hikariConfig.setPassword(env.getProperty("datasource." + dbName + ".password"));
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(HikariDataSource.class);
            builder.addConstructorArgValue(hikariConfig);
            if ("master".equals(dbName)) {
                builder.setPrimary(true);
                defaultListableBeanFactory.registerBeanDefinition("dataSource", builder.getBeanDefinition());
            } else {
                defaultListableBeanFactory.registerBeanDefinition(dbName + "DataSource", builder.getBeanDefinition());
            }
        }
    }

    @Override
    public void setEnvironment(Environment env) {
        this.env = env;
    }
}
